package org.jeecg.modules.mes.storage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.storage.entity.MesWarehouseArea;
import org.jeecg.modules.mes.storage.entity.MesWarehouseAreaLocation;
import org.jeecg.modules.mes.storage.service.IMesWarehouseAreaLocationService;
import org.jeecg.modules.mes.storage.service.IMesWarehouseAreaService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 仓库区域表
 * @Author: jeecg-boot
 * @Date: 2021-05-13
 * @Version: V1.0
 */
@Api(tags = "仓库区域表")
@RestController
@RequestMapping("/storage/mesWarehouseArea")
@Slf4j
public class MesWarehouseAreaController extends JeecgController<MesWarehouseArea, IMesWarehouseAreaService> {

    @Autowired
    private IMesWarehouseAreaService mesWarehouseAreaService;

    @Autowired
    private IMesWarehouseAreaLocationService mesWarehouseAreaLocationService;


    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param mesWarehouseArea
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "仓库区域表-分页列表查询")
    @ApiOperation(value = "仓库区域表-分页列表查询", notes = "仓库区域表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesWarehouseArea mesWarehouseArea,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MesWarehouseArea> queryWrapper = QueryGenerator.initQueryWrapper(mesWarehouseArea, req.getParameterMap());
        Page<MesWarehouseArea> page = new Page<MesWarehouseArea>(pageNo, pageSize);
        IPage<MesWarehouseArea> pageList = mesWarehouseAreaService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    @AutoLog(value = "仓库区域表-列表模糊查询")
    @ApiOperation(value = "仓库区域表-列表模糊查询", notes = "仓库区域表-列表模糊查询")
    @GetMapping(value = "/queryListByAreaCode")
    public Result<?> queryListByAreaCode(@RequestParam(name = "areaCode") String areaCode) {
        return mesWarehouseAreaService.queryListByAreaCode(areaCode);
    }

    /**
     * 添加
     *
     * @param mesWarehouseArea
     * @return
     */
    @AutoLog(value = "仓库区域表-添加")
    @ApiOperation(value = "仓库区域表-添加", notes = "仓库区域表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesWarehouseArea mesWarehouseArea) {
        return mesWarehouseAreaService.add(mesWarehouseArea);
    }

    /**
     * 编辑
     *
     * @param mesWarehouseArea
     * @return
     */
    @AutoLog(value = "仓库区域表-编辑")
    @ApiOperation(value = "仓库区域表-编辑", notes = "仓库区域表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesWarehouseArea mesWarehouseArea) {
        return mesWarehouseAreaService.edit(mesWarehouseArea);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库区域表-通过id删除")
    @ApiOperation(value = "仓库区域表-通过id删除", notes = "仓库区域表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mesWarehouseAreaService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "仓库区域表-批量删除")
    @ApiOperation(value = "仓库区域表-批量删除", notes = "仓库区域表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesWarehouseAreaService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesWarehouseArea mesWarehouseArea) {
        return super.exportXls(request, mesWarehouseArea, MesWarehouseArea.class, "仓库区域表");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesWarehouseArea.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-仓库区域位置表-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "仓库区域位置表-通过主表ID查询")
    @ApiOperation(value = "仓库区域位置表-通过主表ID查询", notes = "仓库区域位置表-通过主表ID查询")
    @GetMapping(value = "/listMesWarehouseAreaLocationByMainId")
    public Result<?> listMesWarehouseAreaLocationByMainId(MesWarehouseAreaLocation mesWarehouseAreaLocation,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<MesWarehouseAreaLocation> queryWrapper = QueryGenerator.initQueryWrapper(mesWarehouseAreaLocation, req.getParameterMap());
        Page<MesWarehouseAreaLocation> page = new Page<MesWarehouseAreaLocation>(pageNo, pageSize);
        IPage<MesWarehouseAreaLocation> pageList = mesWarehouseAreaLocationService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 列表模糊查询
     */
    @AutoLog(value = "仓库区域位置表-列表模糊查询")
    @ApiOperation(value = "仓库区域位置表-列表模糊查询", notes = "仓库区域位置表-列表模糊查询")
    @GetMapping(value = "/queryListByLocationCode")
    public Result<?> queryListByLocationCode(@RequestParam(name = "areaId") String areaId,
                                             @RequestParam(name = "locationCode") String locationCode) {
        return mesWarehouseAreaService.queryListByLocationCode(areaId, locationCode);
    }

    /**
     * 添加
     *
     * @param mesWarehouseAreaLocation
     * @return
     */
    @AutoLog(value = "仓库区域位置表-添加")
    @ApiOperation(value = "仓库区域位置表-添加", notes = "仓库区域位置表-添加")
    @PostMapping(value = "/addMesWarehouseAreaLocation")
    public Result<?> addMesWarehouseAreaLocation(@RequestBody MesWarehouseAreaLocation mesWarehouseAreaLocation) {
        return mesWarehouseAreaLocationService.addMesWarehouseAreaLocation(mesWarehouseAreaLocation);
    }

    /**
     * 编辑
     *
     * @param mesWarehouseAreaLocation
     * @return
     */
    @AutoLog(value = "仓库区域位置表-编辑")
    @ApiOperation(value = "仓库区域位置表-编辑", notes = "仓库区域位置表-编辑")
    @PutMapping(value = "/editMesWarehouseAreaLocation")
    public Result<?> editMesWarehouseAreaLocation(@RequestBody MesWarehouseAreaLocation mesWarehouseAreaLocation) {
        return mesWarehouseAreaLocationService.editMesWarehouseAreaLocation(mesWarehouseAreaLocation);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库区域位置表-通过id删除")
    @ApiOperation(value = "仓库区域位置表-通过id删除", notes = "仓库区域位置表-通过id删除")
    @DeleteMapping(value = "/deleteMesWarehouseAreaLocation")
    public Result<?> deleteMesWarehouseAreaLocation(@RequestParam(name = "id", required = true) String id) {
        return mesWarehouseAreaLocationService.deleteMesWarehouseAreaLocation(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "仓库区域位置表-批量删除")
    @ApiOperation(value = "仓库区域位置表-批量删除", notes = "仓库区域位置表-批量删除")
    @DeleteMapping(value = "/deleteBatchMesWarehouseAreaLocation")
    public Result<?> deleteBatchMesWarehouseAreaLocation(@RequestParam(name = "ids", required = true) String ids) {
        return mesWarehouseAreaLocationService.deleteBatchMesWarehouseAreaLocation(Arrays.asList(ids.split(",")));
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMesWarehouseAreaLocation")
    public ModelAndView exportMesWarehouseAreaLocation(HttpServletRequest request, MesWarehouseAreaLocation mesWarehouseAreaLocation) {
        // Step.1 组装查询条件
        QueryWrapper<MesWarehouseAreaLocation> queryWrapper = QueryGenerator.initQueryWrapper(mesWarehouseAreaLocation, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MesWarehouseAreaLocation> pageList = mesWarehouseAreaLocationService.list(queryWrapper);
        List<MesWarehouseAreaLocation> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "仓库区域位置表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, MesWarehouseAreaLocation.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("仓库区域位置表报表", "导出人:" + sysUser.getRealname(), "仓库区域位置表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMesWarehouseAreaLocation/{mainId}")
    public Result<?> importMesWarehouseAreaLocation(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesWarehouseAreaLocation> list = ExcelImportUtil.importExcel(file.getInputStream(), MesWarehouseAreaLocation.class, params);
                for (MesWarehouseAreaLocation temp : list) {
                    temp.setAreaId(mainId);
                }
                long start = System.currentTimeMillis();
                mesWarehouseAreaLocationService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库区域位置表通过主表ID查询")
    @ApiOperation(value = "仓库区域位置表主表ID查询", notes = "仓库区域位置表-通主表ID查询")
    @GetMapping(value = "/queryMesWarehouseAreaLocationByMainId")
    public Result<?> queryMesWarehouseAreaLocationListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MesWarehouseAreaLocation> mesWarehouseAreaLocationList = mesWarehouseAreaLocationService.selectByMainId(id);
        return Result.ok(mesWarehouseAreaLocationList);
    }
    /*--------------------------------子表处理-仓库区域位置表-end----------------------------------------------*/


}
